<template>
  <el-form label-width="100px">
    <el-form-item label="SKU名称">
      <el-input
        placeholder="请输入SKU名称"
        v-model="skuParams.skuName"
      ></el-input>
    </el-form-item>
    <el-form-item label="价格(元)">
      <el-input
        placeholder="价格(元)"
        type="number"
        v-model.number="skuParams.price"
      ></el-input>
    </el-form-item>
    <el-form-item label="重量(kg)">
      <el-input
        placeholder="重量(kg)"
        type="number"
        v-model.number="skuParams.weight"
      ></el-input>
    </el-form-item>
    <el-form-item label="SKU描述">
      <el-input
        placeholder="请输入描述"
        type="textarea"
        v-model="skuParams.skuDesc"
      ></el-input>
    </el-form-item>
    <el-form-item label="平台属性">
      <el-form :inline="true">
        <el-form-item
          v-for="item in attrArr"
          :key="item.id"
          :label="item.attrName"
        >
          <el-select style="width: 300px" v-model="item.attrIdAndValueId">
            <el-option
              v-for="attrValue in item.attrValueList"
              :key="attrValue.id"
              :label="attrValue.valueName"
              :value="`${item.id}:${attrValue.id}`"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>
    <el-form-item label="销售属性">
      <el-form :inline="true">
        <el-form-item
          v-for="item in saleArr"
          :key="item.id"
          :label="item.saleAttrName"
        >
          <el-select style="width: 200px" v-model="item.saleIdAndValueId">
            <el-option
              v-for="saleAttrValue in item.spuSaleAttrValueList"
              :key="saleAttrValue.id"
              :label="saleAttrValue.saleAttrValueName"
              :value="`${item.id}:${saleAttrValue.id}`"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>
    <el-form-item label="图片名称">
      <el-table border :data="imgArr" ref="table">
        <el-table-column
          type="selection"
          width="80px"
          align="center"
        ></el-table-column>
        <el-table-column label="图片" align="center">
          <template #="{ row, $index }">
            <img :src="row.imgUrl" alt="" style="width: 100px; height: 100px" />
          </template>
        </el-table-column>
        <el-table-column
          label="名称"
          align="center"
          prop="imgName"
        ></el-table-column>
        <el-table-column label="操作" align="center">
          <template #="{ row, $index }">
            <el-button type="primary" size="small" @click="handler(row)"
              >设为默认</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="save">保存</el-button>
      <el-button type="primary" @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { reqAttr } from "@/api/product/attr";
import {
  reqSpuImageList,
  reqSpuHasSaleAttr,
  reqAddSku,
} from "@/api/product/spu";
import { ElMessage } from "element-plus";

// 存储平台属性
const attrArr = ref<any>([]);
// 存储销售属性
const saleArr = ref<any>([]);
// 存储图片数据
const imgArr = ref<any>([]);

// 收集SKU的参数
const skuParams = ref<any>({});
// 获取table组件实例
const table = ref();
// 当前子组件的方法对外暴露
const initSkuData = async (c1Id: number, c2Id: number, spu: any) => {
  // 收集数据
  skuParams.value.category3Id = spu.category3Id;
  skuParams.value.spuId = spu.id;
  skuParams.value.tmId = spu.tmId;
  // 获取全部品牌属性
  const res = await reqAttr(c1Id, c2Id, spu.category3Id);
  attrArr.value = res.data;
  // 获取对应的销售属性
  const res2 = await reqSpuHasSaleAttr(spu.id);
  saleArr.value = res2.data;
  // 获取照片墙数据
  const res3 = await reqSpuImageList(spu.id);
  imgArr.value = res3.data;

  console.log(attrArr.value);
  console.log(saleArr.value);
  console.log(imgArr.value);
};

// 取消按钮回调
const cancel = () => {
  emit("changeScene", { flag: 0 });
};

// 设置默认图片按钮回调
const handler = (row: any) => {
  // 清除之前选中的图片
  table.value.clearSelection();
  // 复选框选中
  table.value.toggleRowSelection(row, true);
  skuParams.value.skuDefaultImg = row.imgUrl;
};

// 保存按钮回调
const save = async () => {
  // 整理参数
  // 1. 平台属性
  skuParams.value.skuAttrValueList = attrArr.value.reduce(
    (prev: any, next: any) => {
      if (next.attrIdAndValueId) {
        const [attrId, valueId] = next.attrIdAndValueId.split(":");
        prev.push({
          attrId: Number(attrId),
          valueId: Number(valueId),
        });
      }
      return prev;
    },
    []
  );

  // 2. 销售属性
  skuParams.value.skuSaleAttrValueList = saleArr.value.reduce(
    (prev: any, next: any) => {
      if (next.saleIdAndValueId) {
        const [saleId, valueId] = next.saleIdAndValueId.split(":");
        prev.push({
          saleAttrId: Number(saleId), // 注意字段名可能是 saleAttrId（根据后端字段）
          saleAttrValueId: Number(valueId),
        });
      }
      return prev;
    },
    []
  );

  // 添加SKU请求
  const res = await reqAddSku(skuParams.value);
  if (res.code === 200) {
    ElMessage.success("添加成功");
    // 添加成功后，跳转到列表页
    emit("changeScene", { flag: 0 });
  } else {
    ElMessage.error("添加失败");
  }
};

// 对外暴露的方法
defineExpose({
  initSkuData,
});
// 自定义事件
const emit = defineEmits(["changeScene"]);
</script>

<style scoped></style>
